﻿using System;
using System.IO;
using System.Windows.Forms;
using Microsoft.Office.Tools.Ribbon;
using Visio.ForwardEngineer.DataModel;
using Visio.ForwardEngineer.UserInterface;
using IVisio = Microsoft.Office.Interop.Visio;
using System.Runtime.InteropServices;

namespace Visio.ForwardEngineer
{
    public partial class ForwardEngineerRibbon
    {
        private void ForwardEngineerRibbon_Load(object sender, RibbonUIEventArgs e)
        {

        }

        private void buttonForwardEngineer_Click(object sender, RibbonControlEventArgs e)
        {
            IVisio.Application app;

            object visioObject = Marshal.GetActiveObject("Visio.Application");
            app = visioObject as IVisio.Application;

            if (app.ActiveDocument == null)
            {
                MessageBox.Show("Open a document before calling the forward engineer!");
                return;
            }

            using (ForwardEngineerForm form = new ForwardEngineerForm())
            {
                if (form.ShowDialog() == DialogResult.OK)
                {
                    ModelStructure dataModel;
                    ModelTransformer.ValidateModelStructure(form.ModelFileName);

                    if (form.SpecificTables)
                    {
                        dataModel = ModelTransformer.GetModelStructure(form.ModelFileName, form.SpecifiedTablesSelected);
                    }
                    else
                    {
                        dataModel = ModelTransformer.GetModelStructure(form.ModelFileName);
                    }

                    StreamWriter outputFile = File.CreateText(form.OutputFileName);

                    if (form.UseTransactions)
                    {
                        outputFile.WriteLine(dataModel.ScriptUseTransactionsStart());
                    }

                    if (!string.IsNullOrEmpty(form.DatabaseName))
                    {
                        outputFile.WriteLine(string.Format("USE [{0}]", form.DatabaseName));
                        outputFile.WriteLine("GO");
                    }

                    if (form.GenerateDropDatabase)
                    {
                        outputFile.WriteLine(dataModel.ScriptDropDatabase(form.DatabaseName));
                    }

                    if (form.GenerateCreateDatabase)
                    {
                        outputFile.WriteLine(dataModel.ScriptCreateDatabase(form.DatabaseName));
                    }

                    //  Generate table create
                    foreach (TableStructure table in dataModel.Tables.Values)
                    {
                        outputFile.WriteLine(table.ScriptCreateTable());
                        outputFile.WriteLine(table.ScriptCreateIndexes());
                    }

                    //  Generate Foreign keys
                    foreach (TableStructure table in dataModel.Tables.Values)
                    {
                        outputFile.WriteLine(table.ScriptCreateForeignKeys());
                    }

                    //  Optionally appends the SQL code to the script, to complete database generation
                    if (form.AppendAdditionalCode)
                    {
                        outputFile.WriteLine("GO");
                        outputFile.WriteLine("---------------------------------------------------------------------------------------");
                        outputFile.WriteLine("-- Additional code from " + form.AppendAdditionalCodeFileName);
                        outputFile.WriteLine("---------------------------------------------------------------------------------------");
                        outputFile.WriteLine();
                        StreamReader additionalCodeReader = File.OpenText(form.AppendAdditionalCodeFileName);
                        while (!additionalCodeReader.EndOfStream)
                        {
                            string newLine = additionalCodeReader.ReadLine();
                            outputFile.WriteLine(newLine);
                        }
                        additionalCodeReader.Close();
                        outputFile.WriteLine("---------------------------------------------------------------------------------------");
                        outputFile.WriteLine("-- End of code from " + form.AppendAdditionalCodeFileName);
                        outputFile.WriteLine("---------------------------------------------------------------------------------------");
                        outputFile.WriteLine("GO");
                    }


                    if (form.UseTransactions)
                    {
                        outputFile.WriteLine(dataModel.ScriptUseTransactionsEnd());
                    }

                    outputFile.Close();

                    //  Optionally opens the script with SSMS
                    if (form.OpenScript)
                    {
                        try
                        {
                            System.Diagnostics.Process.Start(form.OutputFileName);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("Unable to open the output file: " + ex.Message);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// Validates the data model
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonValidate_Click(object sender, RibbonControlEventArgs e)
        {
            string[] modelNames = ModelTransformer.GetModels();
            if (modelNames.Length > 1)
            {
                using (ValidateModelForm form = new ValidateModelForm())
                {
                    if (form.ShowDialog() == DialogResult.OK)
                    {
                        ModelTransformer.ValidateModelStructure(form.ModelFileName);
                    }
                }
            }
            else
            {
                if (modelNames.Length == 1)
                {
                    ModelTransformer.ValidateModelStructure(modelNames[0]);
                }
                else
                {
                    MessageBox.Show("No model to validate");
                }
            }
        }

    }
}